package com.gexiaobao.pigeon.ui.adapter

import androidx.core.content.ContextCompat
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.DataBindBaseViewHolder
import com.gexiaobao.pigeon.app.model.bean.VisitPersonResponse
import com.gexiaobao.pigeon.databinding.ItemVisitPersonBinding

/**
 * @Author      : hxw
 * @Date        : 2025/1/13 16:25
 * @Describe    :
 */
class AdapterVisitPerson(data: ArrayList<VisitPersonResponse>) :
    BaseQuickAdapter<VisitPersonResponse, DataBindBaseViewHolder>(R.layout.item_visit_person, data) {

    var isItemClickable = true // 控制是否可点击
    private var selectedPosition: Int = -1 // 记录选中项的位置
    private var onItemClickPersonListener: OnItemClickPersonListener? = null

    override fun convert(holder: DataBindBaseViewHolder, item: VisitPersonResponse) {
        val binding = DataBindBaseViewHolder.getBinding(holder) as ItemVisitPersonBinding
        binding.data = item
        binding.executePendingBindings()//防止列表抖动

        // 控制是否可点击
        holder.itemView.isEnabled = isItemClickable
        holder.itemView.isClickable = isItemClickable

        // 根据选中状态设置样式
        if (item.isSelected) {
            holder.setBackgroundResource(R.id.tvItemVisitPerson, R.drawable.border_red3) // 设置选中背景
            holder.setTextColor(R.id.tvItemVisitPerson, ContextCompat.getColor(context, R.color.color_f65a5a))
        } else {
            holder.setBackgroundResource(R.id.tvItemVisitPerson, R.drawable.border_gray3) // 默认背景
            holder.setTextColor(R.id.tvItemVisitPerson, ContextCompat.getColor(context, R.color.color_999999))
        }

        // 点击事件处理
        holder.itemView.setOnClickListener {
            val position = holder.adapterPosition
            if (selectedPosition != position) {
                if (selectedPosition != -1) {
                    data[selectedPosition].isSelected = false
                    notifyItemChanged(selectedPosition)
                }
            }
            selectedPosition = position
            data[selectedPosition].isSelected = true
            notifyItemChanged(selectedPosition)
            onItemClickPersonListener?.onItemPersonVisit(position + 1)
        }
    }

    fun setSelectedPosition(position: Int) {
        selectedPosition = position
    }

    // 定义接口
    interface OnItemClickPersonListener {
        fun onItemPersonVisit(personNum: Int)
    }

    // 设置接口的实现者
    fun setOnItemPersonPassedListener(listener: OnItemClickPersonListener) {
        this.onItemClickPersonListener = listener
    }
}